/*
 * Copyright 2016 czy1121
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.badgebutton_ohos;


import ohos.agp.colors.RgbColor;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Component.EstimateSpec;
import ohos.agp.components.Text;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.components.flex.AlignContent;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.Rect;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;

import java.util.jar.Attributes;

public final class BadgeButton extends Text implements Component.DrawTask, Component.EstimateSizeListener {

    private BadgeDrawable mBadgeDrawable;

    public BadgeButton(Context context) {
        this(context, null);
    }

    public BadgeButton(Context context, AttrSet attrs) {
        this(context, attrs, null);
    }

    public BadgeButton(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);

    /*    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BadgeButton);
        String badgeText = a.getString(R.styleable.BadgeButton_btnBadgeText);
        int badgeColor = a.getColor(R.styleable.BadgeButton_btnBadgeColor, 0xffFF4081);
        int badgeHeight = a.getDimensionPixelSize(R.styleable.BadgeButton_btnBadgeHeight, (int) (getResources().getDisplayMetrics().density * 12));
        boolean badgeVisible = a.getBoolean(R.styleable.BadgeButton_btnBadgeVisible, false);
        a.recycle();*/

        String badgeText = null;
        if (attrs.getAttr(name).isPresent()) {
            badgeText= attrs.getAttr(name).get().getStringValue();
        }
        int badgeColor = 0;
        if (attrs.getAttr(name).isPresent()) {
            badgeColor= attrs.getAttr(name).get().getIntegerValue();
        }
        int badgeHeight = 0;
        if (attrs.getAttr(name).isPresent()) {
            badgeHeight= attrs.getAttr(name).get().getIntegerValue();
        }
        boolean badgeVisible = false;
        if (attrs.getAttr(name).isPresent()) {
            badgeVisible= attrs.getAttr(name).get().getBoolValue();
        }

        mBadgeDrawable = new BadgeDrawable(badgeHeight, badgeColor);
        mBadgeDrawable.setVisible(badgeVisible);
        mBadgeDrawable.setText(badgeText);

        //setIcon(getCompoundDrawables()[1]);
        setIcon(getAroundElements()[1]);

    }


    public BadgeButton setIcon(Element drawable) {
        if (drawable != null && drawable.getBounds().isEmpty()) {
            drawable.setBounds(0, 0, drawable.getWidth(), drawable.getHeight());
        }
      //  Drawable[] cds = getCompoundDrawables();
        Element[] cds = getAroundElements();
        //setCompoundDrawables(cds[0], drawable, cds[2], cds[3]);
        setAroundElements(cds[0], drawable, cds[2], cds[3]);
        return this;
    }

    @Override
    public void setText(String text) {
        super.setText(text);
    }

    public BadgeButton setBadgeText(String text) {
        mBadgeDrawable.setText(text);
        return this;
    }

    public BadgeButton setBadgeVisible(boolean visible) {
        mBadgeDrawable.setVisible(visible);
        return this;
    }



 /*   @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

    }*/

    @Override
    public void onDraw(Component component, Canvas canvas) {
        mBadgeDrawable.drawToCanvas(canvas);
    }

/*    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        if (getAroundElements()[1] != null){
            mBadgeDrawable.layout((width + getAroundElements()[1].getWidth()) / 2, getPaddingTop(), width);
        } else{
            mBadgeDrawable.layout((width + (int) getLayout().getLineWidth(0)) / 2, getPaddingTop(), width);

        }

    }*/

    @Override
    public boolean onEstimateSize(int i, int i1) {
        int width = getEstimatedWidth();
        if (getAroundElements()[1] != null){
            mBadgeDrawable.layout((width + getAroundElements()[1].getWidth()) / 2, getPaddingTop(), width);
        } else{
            mBadgeDrawable.layout((width + (int) getBaseLine(0)) / 2, getPaddingTop(), width);

        }
        return true;
    }

    private static class BadgeDrawable extends ShapeElement implements Element.OnBoundsChangeListener {
        private String mText;
        private boolean mIsVisible;
        private Paint mPaint = new Paint();
        //private Paint mPaint = new Paint(Paint.alias);

        private int mHeight = 0;

        public BadgeDrawable(int height, int color) {
            mPaint.setAntiAlias(true);
           // setColor(color);
            setRgbColor(new RgbColor(color));
           // mPaint.setColor(0xffffffff);
            mPaint.setColor(Color.WHITE);
            mPaint.setTextAlign(TextAlignment.CENTER);
            mPaint.setTextSize((int) (height * 0.8f));

            mHeight = height;
        }

        void layout(int x, int y, int max) {
            Rect rect = getBounds();
           // rect.offsetTo(Math.min(x - rect.width() / 2, max - rect.width() - (int) (0.2f * mHeight)), Math.max(0, y - rect.height() / 2));
            rect.offset(Math.min(x - rect.getWidth() / 2, max - rect.getWidth() - (int)(0.2f * mHeight)), Math.max(0, y - rect.getHeight() / 2));
            setBounds(rect);
        }

        void resize(int w, int h) {
            Rect rect = getBounds();
            setBounds(rect.left, rect.top, rect.left + w, rect.top + h);
            release();

        }

        public void setText(String text) {
            mText = text;
            if (mText==null||mText.equals("")) {
                int size = (int) (mHeight * 0.65);
                resize(size, size);
            } else {
                int width = (int) (mPaint.measureText(mText) + 0.4 * mHeight);
                resize(Math.max(width, mHeight), mHeight);
            }
        }

        public void setVisible(boolean visible) {
            if (mIsVisible != visible) {
                release();

            }
            mIsVisible = visible;
        }

   /*     @Override
        protected void onBoundsChange(Rect bounds) {
            super.onBoundsChange(bounds);
            setCornerRadius(getBounds().height() / 2f);
        }*/
        @Override
        public void onBoundsChanged(Element element, Rect rect) {
            setCornerRadius(getBounds().getHeight() / 2f);
        }


   /*     @Override
        public void draw(Canvas canvas) {
            if (!mIsVisible) {
                return;
            }
            super.draw(canvas);
            if (TextUtils.isEmpty(mText)) {
                return;
            }
            canvas.drawText(mText, getBounds().exactCenterX(), getBounds().exactCenterY() - (mPaint.descent() + mPaint.ascent()) / 2, mPaint);
        }*/
        @Override
        public void drawToCanvas(Canvas canvas) {
            if (!mIsVisible) {
                return;
            }
            super.drawToCanvas(canvas);
            if (mText==null||mText.equals("")) {
                return;
            }
           // canvas.drawText(mText, getBounds().exactCenterX(), getBounds().exactCenterY() - (mPaint.descent() + mPaint.ascent()) / 2, mPaint);

            canvas.drawText(mPaint,mText, getBounds().getCenterX(), getBounds().getCenterY() - (mPaint.descent() + mPaint.ascent()) / 2);

        }


    }


}